package com.eol.common.utils;

import cn.hutool.core.codec.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2020/1/4
 * Time: 5:59 AM
 * Description: QrCode
 */
@Component
public class QrCodeUtils {

    @Resource
    private WxMpService wxMpService;

    /**
     * 生成二维码
     *
     * @param message 内容
     */
    public String generateQrCode(String message, int width, int height) {
        String resultImage = "";
        if (!StringUtils.isEmpty(message)) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            @SuppressWarnings("rawtypes")
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
            hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距

            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(message, BarcodeFormat.QR_CODE, width, height, hints);

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, "png", os);
                resultImage = "data:image/png;base64," + Base64.encode(os.toByteArray());

                return resultImage;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param id 用户ID  1:前端用户  2：订单通知用户  3:后台人员
     * @return base64
     */
    public String calQrCode(String id) throws WxErrorException, IOException {
        WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(id, 20 * 24 * 60 * 60);
        File file = wxMpService.getQrcodeService().qrCodePicture(ticket);
        byte[] fileContent = Files.readAllBytes(file.toPath());
        return "data:image/png;base64," + Base64.encode(fileContent);
    }
}
